<template>
  <NModal v-model:show="visible" :title="title" :mask-closable="false" transform-origin="center" preset="card" @after-leave="closeDrawer" class="w-900px">
    <NScrollbar class="h-500px pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="100">
        <NGrid responsive="screen" item-responsive>
          <NFormItemGi span="24 m:12" label="姓名" path="name">
            <NInput v-model:value="model.name" placeholder="请输入姓名" clearable/>
          </NFormItemGi>
          <NFormItemGi span="24 m:12" label="手机号" path="phone">
            <NInput v-model:value="model.phone" placeholder="请输入手机号" clearable/>
          </NFormItemGi>
          <NFormItemGi span="24 m:12" label="邮箱" path="email">
            <NInput v-model:value="model.email" placeholder="请输入邮箱" clearable/>
          </NFormItemGi>
          <NFormItemGi span="24 m:12" label="性别" path="gender">
            <NRadioGroup v-model:value="model.gender" name="gender">
              <NSpace>
                <NRadio v-for="song in state.songs" :key="song.value" :value="song.value">
                  {{ song.label }}
                </NRadio>
              </NSpace>
            </NRadioGroup>
          </NFormItemGi>
          <NFormItemGi span="24 m:12" label="出生日期" path="birthday">
            <NDatePicker class="w-100%" v-model:formatted-value="model.birthday" value-format="yyyy-MM-dd" type="date" clearable/>
          </NFormItemGi>
          <NFormItemGi span="24 m:12" label="入职日期" path="entryDate">
            <NDatePicker class="w-100%" v-model:formatted-value="model.entryDate" value-format="yyyy-MM-dd" type="date" clearable/>
          </NFormItemGi>

          <NFormItemGi span="24 m:12" label="选择组织" path="orgId">
            <NTreeSelect v-model:value="model.orgId" label-field="name" key-field="id" :options="treeOptions"
                         placeholder="请选择所属组织" default-expand-all @update-value="getPositionData" clearable/>
          </NFormItemGi>
          <NFormItemGi span="24 m:12" label="选择职位" path="positionId">
            <NSelect v-model:value="model.positionId" :options="state.position" label-field="name" value-field="id" placeholder="请选择职位" clearable/>
          </NFormItemGi>
          <NFormItemGi span="24 m:12" label="选择主管" path="directorId">
            <NSelect v-model:value="model.directorId" :options="state.userOptions" label-field="name" value-field="id" placeholder="请选择主管"
                     filterable :reset-menu-on-options-change="false" @scroll="handleScroll" @search="getUserList" clearable/>
          </NFormItemGi>
          <NFormItemGi span="24 m:12" label="职级" path="positionLevel">
            <NInput v-model:value="model.positionLevel" placeholder="请输入职级" clearable/>
          </NFormItemGi>
        </NGrid>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">取消</NButton>
        <NButton type="primary" @click="handleSubmit">提交</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<script setup lang="ts">
import {reactive, toRefs,watch,computed,nextTick} from "vue";
import {useFormRules, useNaiveForm} from '@/hooks/common/form';
import {orgSelectTree} from '@/service/api/org-api';
import {getPosition} from '@/service/api/position-api'
import {userPage,userDetail} from '@/service/api/auth'

export type OperateType = NaiveUI.TableOperateType;
const {formRef, validate, restoreValidation} = useNaiveForm();
const {defaultRequiredRule} = useFormRules();

interface Props {
  // 操作类型
  operateType: OperateType;
  // 编辑组织的数据
  rowData?: number;
}

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const props = defineProps<Props>();
const visible = defineModel<boolean>('visible', {
  default: false
});
const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: '新增成员',
    edit: '编辑成员'
  };
  return titles[props.operateType];
});

const state = reactive({
  songs:[
    {label: '男', value: '1'},
    {label: '女', value: '2'}
  ] as  CommonType.Option[],
  treeOptions :[] as Api.SystemManage.OrgTreeType[],
  position:[] as Api.Common.SelectOptions[],
  userOptions:[] as Api.SystemManage.UserInfo[],
  searchUserParam:{
    pageNumber: 1,
    pageSize: 10
  } as Api.SystemManage.SearchUserParam
})

// 转为ref后解构
const {treeOptions} = {...toRefs(state)};

// 监听打开窗口时，逻辑处理
watch(visible, () => {
  if (visible.value) {
    // 清空表单
    Object.assign(model, createDefaultModel());
    // 获取组织选择树的数据
    getOrgSelectTree()
    if (props.operateType === 'edit' && props.rowData) {
      // 查询用户详情
      getUserDetail();
    }
    restoreValidation();
  }
});

type Model = Pick<Api.SystemManage.UserAdd, 'orgId' | 'name' | 'phone' | 'positionId' | 'directorId' | 'gender' | 'email' | 'birthday'| 'entryDate' | 'positionLevel'>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    phone: '',
    name: '',
    orgId: null,
    positionId: null,
    directorId: null,
    gender:'',
    email:'',
    birthday:null,
    entryDate:null,
    positionLevel:''
  }
}

type RuleKey = Exclude<keyof Model, 'directorId' | 'gender' | 'email' | 'birthday'| 'entryDate' | 'positionLevel'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  phone: defaultRequiredRule,
  name: defaultRequiredRule,
  orgId: defaultRequiredRule,
  positionId: defaultRequiredRule
};

// 获取组织选择树的数据
async function getOrgSelectTree(){
  const {data} = await orgSelectTree()
  if (Array.isArray(data)) {
    state.treeOptions = data
  }
}

// 查询用户详情
async function getUserDetail() {
  if (props.rowData != undefined) {
    const {data} = await userDetail(props.rowData)
    Object.assign(model, data);
  }
}

// 取消、关闭弹框
function closeDrawer() {
  num = 1
  // 清空职位
  state.position.length = 0
  // 清空主管
  state.userOptions.length = 0
  visible.value = false;
}

// 提交
async function handleSubmit() {
  // 必填项校验
  await validate();
  const params = getSubmitParams();
  console.log('params: ', params);
  // request
  window.$message?.success('操作成功');
  // 取消、关闭弹框
  closeDrawer();
  // 调用父组件事件
  emit('submitted');
}

function getSubmitParams() {
  const {...params} = model;
  return params;
}

// 查询组织下的职位
async function getPositionData(value: number){
  if(value != null){
    // 查询该组织下的职位
    const {data} = await getPosition(value)
    if (Array.isArray(data)) {
      state.position = data
    }
    await nextTick(() => {
      // 查询组织下的人员
      state.searchUserParam.orgId = value
      state.searchUserParam.searchKey = null
      userPage(state.searchUserParam).then(res => {
          state.userOptions=[...state.userOptions, ...(res.data?.records || [])]
      })
    })
  }else {
    // 清空职位
    state.position = []
    model.positionId = null
    // 清空主管
    state.userOptions=[]
    model.directorId = null
    num = 1
  }
}

let num=1;
async function handleScroll(e: Event){
  const currentTarget = e.currentTarget as HTMLElement
  // 检查是否滚动到底部
  if (currentTarget.scrollTop + currentTarget.offsetHeight >= currentTarget.scrollHeight){
    num++
    // 查询该组织下的职位
    state.searchUserParam.pageNumber = num
    state.searchUserParam.searchKey = null
    const {data} = await userPage(state.searchUserParam)
    state.userOptions=[...state.userOptions, ...(data?.records || [])]
  }
}
// 获取用户
async function getUserList(value:string){
  state.searchUserParam.searchKey = value
  state.searchUserParam.pageNumber = 1
  const {data} = await userPage(state.searchUserParam)
  state.userOptions=[...state.userOptions, ...(data?.records || [])]
}
</script>

<style scoped>

</style>
